﻿using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace TST.SharePointObjects
{
    internal class SiteColumnContentTypeReferences : ObjectReferenceList
    {
        private List<string> _demoItems;

        public SiteColumnContentTypeReferences(LicensingMode licensingMode)
            : base(licensingMode)
        {
            _demoItems = new List<string>();
            if (LicensingMode == LicensingMode.Demo)
            {
                _demoItems = Globals.GetDemoContentTypes();
            }
        }

        public override ObjectReferenceType ObjectReferenceType
        {
            get { return ObjectReferenceType.SiteColumnContentType; }
        }

        internal void Add(SiteObjectList objects, SPWeb web, SPContentType contentType, SPSite site, SPWebApplication webApplication)
        {
            if (LicensingMode == LicensingMode.FullLicense ||
                (LicensingMode == LicensingMode.Demo && _demoItems.Contains(contentType.Parent.Id.ToString().ToLower())))
            {
                foreach (SPFieldLink fieldLink in contentType.FieldLinks)
                {
                    SiteObject siteObject = objects.GetItemById(fieldLink.Id.ToString("B"));
                    if (siteObject != null && siteObject.Index)
                    {
                        if (Globals.MatchingScope(siteObject, webApplication, site, web))
                        {
                            SPField field = web.Fields[fieldLink.Id];
                            string refId = Globals.GetReferenceId(siteObject, field);
                            ObjectReference newReference = new ObjectReference(contentType.Id.ToString(), contentType.Name, refId, ObjectReferenceType.SiteColumnContentType);
                            newReference.Url = string.Format("{0}/_layouts/ManageContentTypeField.aspx?ctype={1}&Field={2}&Fid={3}", web.Url, contentType.Id.ToString(), field.InternalName, System.Web.HttpUtility.UrlEncode(field.Id.ToString()));
                            newReference.SiteTitle = web.Title;
                            newReference.SiteUrl = web.Url;
                            newReference.ListTitle = string.Empty;
                            newReference.ListUrl = string.Empty;
                            Add(newReference);
                        }
                    }
                }
            }
        }
    }
}
